﻿/* 版本记录
 * 0000 20200902  by linson add
 * 0001 
 * */

using System;using GKQC.Language;
using System.Collections.Generic;
using System.Windows.Forms;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Dao;
using GKQC.Common;
using SqlSugar;
using GKQC.DbHelper.Services;
using System.ComponentModel;
using System.Reflection;
using GKQC.DbHelper.ViewModels;

namespace GKQC.Forms
{
    /// <summary>
    /// 辅助资料设置
    /// </summary>
    public partial class FormBaseData : QcFormBase
    {
        UserModel user = null;
        AllDbContext dbContext = null;
        List<BaseDataTypeModel> _Types = new List<BaseDataTypeModel>();
        List<BaseDataModel> _CurrentItems;
        FormStatus formStatus = FormStatus.Browser;
        BaseDataTypeService _Service = null;
        /// <summary>
        /// 打开模式是否是弹窗选择模式
        /// </summary>
        public bool IsSelectForm { get; set; }
        public BaseDataModel SelectedData { get; set; }

        public FormBaseData(UserModel user, AllDbContext dbContext, string billtype="")
        {
            InitializeComponent(); LanguageHelper.SetControlLanguageText(this);
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView2.AutoGenerateColumns = false;
            this.dataGridView1.RowPostPaint += DataGridViewSet.RowPostPaint;
            this.dataGridView2.RowPostPaint += DataGridViewSet.RowPostPaint;
            this.user = user;
            this.dbContext = dbContext;
            if (this.user.UserCode != "oubl")
            {
                Col_Dtl_IsSys.ReadOnly = true;
            }
            _Service = new BaseDataTypeService(this.dbContext);

            try
            {
                BindingTypes();
                this.dataGridView2.CellValueChanged += DataGridView2_CellValueChanged;
                this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
                SetControlsEnable();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        public void SetSelectForm()
        {
            IsSelectForm = true;
            menuStrip1.Visible = false;
        }
        private void DataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (formStatus == FormStatus.Browser) return;
            try
            {

            }catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void Fmain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Application.Exit();
        }

        private void FormUser_Resize(object sender, EventArgs e)
        {

        }

        private void tsmAdd_Click(object sender, EventArgs e)
        {
        }

        void ClearControl()
        {
            //currentUser = new UserModel();
            dataGridView2.Rows.Clear();
        }


        private void tsmSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                dataGridView2.EndEdit();
                if (!this.Validate()) return;

                if(_Service.SaveData(_CurrentItems))
                {
                    QMessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    formStatus = FormStatus.Browser;
                    BindingItems();
                    SetControlsEnable();
                }
                else
                {
                    QMessageBox.Show("保存失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"保存检测项目异常",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            if(dataGridView1.CurrentRow == null)
            {
                QMessageBox.Show("請選擇要編輯的类别!");
                return;
            }

            if (!UserRightService.CheckRight(this, this.user, RightType.Modi))
            {
                //QMessageBox.Show("權限不足!","提示");
                return;
            }
            formStatus = FormStatus.Edit;
            SetControlsEnable();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(dataGridView1.CurrentRow != null)
            {
                BindingItems();
                tsmExit.Enabled = true;
            }
            else
            {
                ClearControl();
                tsmExit.Enabled = false;
            }
        }

        void SetControlsEnable()
        {
            if(formStatus == FormStatus.Browser)
            {
                dataGridView1.Enabled = true;
                dataGridView2.ReadOnly = true;
                dataGridView2.AllowUserToAddRows = false;


                tsmAdd.Enabled = true;
                tsmEdit.Enabled = true;
                tsmDelete.Enabled = true;
                tsmSave.Enabled = false;
                tsmCancel.Enabled = false;
                tsmExit.Enabled = true;
            }
            else
            {
                dataGridView1.Enabled = false;
                dataGridView2.ReadOnly = false;
                dataGridView2.AllowUserToAddRows = true;

                tsmAdd.Enabled = false;
                tsmEdit.Enabled = false;
                tsmDelete.Enabled = false;
                tsmSave.Enabled = true;
                tsmCancel.Enabled = true;
                tsmExit.Enabled = false;
            }

            if (dataGridView1.CurrentRow == null) tsmEdit.Enabled = false;
            else tsmEdit.Enabled = true;
        }

        private void tsmCancel_Click(object sender, EventArgs e)
        {
            formStatus = FormStatus.Browser;
            BindingItems();
            SetControlsEnable();
        }

        void BindingTypes()
        {
            try
            {
                BaseDataTypeModel type = new BaseDataTypeModel();
                type.TypeCode = "ORT";
                type.TypeName = "试验类型";
                _Types.Add(type);
                if(_Types != null)
                {
                    dataGridView1.DataSource = new BindingList<BaseDataTypeModel>(_Types);
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "查询检测类别异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

       
        void BindingItems()
        {
            try
            {
                string typecode = string.Empty;
                string typename = string.Empty;
                string items = string.Empty;
                GetCurrentCode(out typecode, out typename);
                if (!string.IsNullOrWhiteSpace(typecode))
                {
                    _CurrentItems = _Service.GetDatas(typecode);
                }

                if (_CurrentItems == null) _CurrentItems = new List<BaseDataModel>();
                dataGridView2.DataSource = new BindingList<BaseDataModel>(_CurrentItems);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message ,"異常S0006");
            }
        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }


        void GetCurrentCode(out string typeCode,out string typeName)
        {
            typeCode = typeName = string.Empty;
            try
            {
                if (dataGridView1.CurrentRow != null)
                {
                    var r = dataGridView1.CurrentRow.DataBoundItem;
                    if (r != null)
                    {
                        PropertyInfo p = r.GetType().GetProperty("TypeCode");
                        if (p != null)
                        {
                            var v = p.GetValue(r, null);
                            if(v!= null)
                            typeCode =v.ToString();
                        }

                        p = r.GetType().GetProperty("TypeName");
                        if (p != null)
                        {
                            var v = p.GetValue(r, null);
                            if (v != null)
                                typeName = v.ToString();
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null)
            {
                BindingItems();
                tsmEdit.Enabled = true;
            }
            else
            {
                ClearControl();
                tsmEdit.Enabled = false;
            }
        }

        private void dataGridView2_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            try
            {
                string typecode, typename;
                GetCurrentCode(out typecode, out typename);
                e.Row.Cells["Col_Dtl_TypeCode"].Value = typecode;
                e.Row.Cells["Col_Dtl_TypeName"].Value = typename;
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (formStatus != FormStatus.Browser) return;

                if (dataGridView2.CurrentRow == null)
                {
                    QMessageBox.ShowInformation("请选中要删除的行");
                    return;
                }

                string typecode = string.Empty;
                string typename = string.Empty;
                string items = string.Empty;

                GetCurrentCode(out typecode, out typename);
                BaseDataModel m = dataGridView2.CurrentRow.DataBoundItem as BaseDataModel;
                if (m == null) return;

                if(m.IsSys ==1)
                {
                    QMessageBox.ShowError("不能删除系统内置资料");
                }

                if (QMessageBox.ShowQuestion("即将删除" + typename + "下的项目" + m.Name)
                    == DialogResult.Cancel)
                    return;

                dbContext.QcDb.Deleteable<BaseDataModel>()
                    .Where(t => t.TypeCode == m.TypeCode && t.Code == m.Code).ExecuteCommand();

                dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(
                    0, dataGridView1.CurrentRow.Index));

                SysLogService.Log(dbContext, this.user, this, "删除", m.TypeCode + ":" + m.Code,
                    m.ToJson());
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0006");
            }
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
        }

        private void dataGridView2_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if(IsSelectForm)
            {
                if (dataGridView2.Rows.Count == 0 || dataGridView2.CurrentRow == null)
                {
                    this.DialogResult = DialogResult.Cancel;
                }
                else if (dataGridView2.CurrentRow != null)
                {
                    SelectedData = dataGridView2.CurrentRow.DataBoundItem as BaseDataModel;
                    this.DialogResult = DialogResult.OK;
                }
            }
        }
    }
}
